package org.llc.gof.structure.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author harvey
 */
public class CglibProxy implements MethodInterceptor {

    private Enhancer enhancer = new Enhancer();

    /**覆盖MethodInterceptor接口的getProxy()方法，设置*/
    public Object getProxy(Class clazz) {
        //设者要创建子类的类
        enhancer.setSuperclass(clazz);
        //设置回调的对象
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例,
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args,
                            MethodProxy proxy) throws Throwable {
        System.out.println("AOP before");
        //通过代理类实例调用父类的方法，即是目标业务类方法的调用
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("AOP after");
        return result;
    }
}
